package com.atguigu.schedule.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.atguigu.schedule.pojo.StartRecordingRequest;
import com.atguigu.schedule.pojo.RecordingResponse;
import com.atguigu.schedule.pojo.RecordingStatus;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 自动录制服务
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AutoRecordingService {
    
    private final SrsService srsService;
    private final VideoRecordingService recordingService;
    private final RecordingConfigService configService;
    
    private boolean isAutoRecording = false;
    private String currentRecordingId = null;
    
    /**
     * 启动自动录制
     */
    public void startAutoRecording() {
        if (isAutoRecording) {
            log.warn("自动录制已在运行中");
            return;
        }
        
        try {
            // 检查SRS服务状态
            if (!srsService.checkSrsStatus()) {
                log.error("SRS服务不可用，无法启动自动录制");
                return;
            }
            
            // 开始录制
            StartRecordingRequest request = new StartRecordingRequest();
            request.setStreamName("livestream");
            request.setDescription("自动录制 - " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            request.setDuration(24 * 3600); // 24小时
            
            RecordingResponse response = recordingService.startRecording(request);
            
            if (response != null) {
                isAutoRecording = true;
                currentRecordingId = response.getId().toString();
                log.info("✅ 自动录制启动成功，录制ID: {}", currentRecordingId);
            } else {
                log.error("❌ 自动录制启动失败：recordingService.startRecording()返回null");
            }
            
        } catch (Exception e) {
            log.error("❌ 启动自动录制失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 停止自动录制
     */
    public void stopAutoRecording() {
        if (!isAutoRecording || currentRecordingId == null) {
            log.warn("没有正在运行的自动录制");
            return;
        }
        
        try {
            recordingService.stopRecording(Long.valueOf(currentRecordingId));
            isAutoRecording = false;
            currentRecordingId = null;
            log.info("自动录制停止成功");
            
        } catch (Exception e) {
            log.error("停止自动录制失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 检查录制状态并自动重启
     */
    @Scheduled(fixedRate = 300000) // 每5分钟检查一次
    public void checkRecordingStatus() {
        if (!isAutoRecording) {
            return;
        }
        
        try {
            // 检查当前录制状态
            RecordingResponse status = recordingService.getRecordingStatus(Long.valueOf(currentRecordingId));
            
            if (status.getStatus() != RecordingStatus.RECORDING) {
                log.warn("录制状态异常，尝试重启录制");
                stopAutoRecording();
                Thread.sleep(5000); // 等待5秒
                startAutoRecording();
            }
            
        } catch (Exception e) {
            log.error("检查录制状态失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 每日凌晨重启录制（避免单次录制时间过长）
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void dailyRestartRecording() {
        log.info("执行每日录制重启");
        stopAutoRecording();
        try {
            Thread.sleep(10000); // 等待10秒
            startAutoRecording();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    /**
     * 获取自动录制状态
     */
    public Map<String, Object> getAutoRecordingStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("isAutoRecording", isAutoRecording);
        status.put("currentRecordingId", currentRecordingId);
        status.put("srsStatus", srsService.checkSrsStatus());
        return status;
    }
}
